package main

import (
	"flag"
	"fmt"
	"io"
	"io/ioutil"
	"log"
	"os"
	"os/exec"
	"path/filepath"
	"strings"
	"sync"
	"time"

	"gitee.com/dark.H/go-remote-repl/thirtyapi"

	"gitee.com/dark.H/go-remote-repl/cli"
	"github.com/briandowns/spinner"
)

func main() {
	var a bool
	var b bool
	var c string
	var e string
	var s string
	flag.StringVar(&e, "e", "", "run python3")
	flag.BoolVar(&a, "d", false, "true to print")
	flag.BoolVar(&b, "b", false, "true to print2")
	flag.StringVar(&c, "c", "", " print3 sdf")
	flag.StringVar(&s, "s", "", "test shell")

	cli.APIParse()
	if a {
		println("good !!!")
		fmt.Println(thirtyapi.SimpleAPIParsse("pip"))
	}
	if e != "" {
		cmd := exec.Command("bash", "-c", "python3 "+e+" -s asdf")
		stdout, _ := cmd.StdoutPipe()
		stderr, _ := cmd.StderrPipe()
		if err := cmd.Start(); err != nil {
			log.Printf("Error executing command: %s......\n", err.Error())
			log.Fatal(err)
		}
		var wg sync.WaitGroup
		go func() {
			for {
				time.Sleep(1 * time.Second)

			}
		}()
		wg.Add(1)
		go func() {
			defer wg.Done()
			io.Copy(os.Stdout, stdout)
		}()

		wg.Add(1)
		go func() {
			defer wg.Done()
			io.Copy(os.Stderr, stderr)
		}()
		wg.Wait()
		cmd.Wait()
		time.Sleep(44 * time.Second)
		// ff := bufio.NewReader(re)

	}

	if s != "" {
		as := strings.Fields(s)
		c := exec.Command(as[0], as[1:]...)
		c.Stdin = os.Stdin
		oo, err := c.Output()
		if err != nil {
			fmt.Println(err)
		}
		fmt.Println(string(oo))
		os.Exit(0)
	}
	if b {
		fmt.Println("adsfdsaf adsfsd")
		time.Sleep(2 * time.Second)
		s := spinner.New(spinner.CharSets[27], 100*time.Millisecond) // Build our new spinner
		s.Start()                                                    // Start the spinner

		filepath.Walk("/tmp/", func(path string, f os.FileInfo, err error) error {
			if !f.IsDir() {
				fmt.Println(path, f.ModTime())
				time.Sleep(300 * time.Millisecond)
			}
			return nil
		})
		time.Sleep(4 * time.Second) // Run for some time to simulate work
		s.Stop()
	}

	if c != "" {
		b, e := ioutil.ReadFile(c)
		if e != nil {

		}
		fmt.Println(string(b))
		// fmt.Println(thirtyapi.SimpleAPIParsse(c))
	}
}
